package rs.dalao.syc.user.pay.controller;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import rs.dalao.syc.common.response.JsonResult;
import rs.dalao.syc.common.response.ServiceCode;
import rs.dalao.syc.user.pay.config.AlipayConfig;
import rs.dalao.syc.user.pay.dao.persist.mapper.OrdersMapper;
import rs.dalao.syc.user.pay.pojo.entity.Orders;
import rs.dalao.syc.user.pay.service.IOrderService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

// xjlugv6874@sandbox.com
// 9428521.24 - 30 = 9428491.24 + 30 = 9428521.24
@RestController
@RequestMapping("/alipay")
@Slf4j
public class PayController {

    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";

    @Autowired
    private AlipayConfig aliPayConfig;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private IOrderService service;


    @GetMapping("/pay") // &subject=xxx&traceNo=xxx&totalAmount=xxx
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, "9021000125605862",
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        System.out.println("fjhgjghjghjgj" + aliPay.getTraceNo());
        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        JSONObject bizContent = new JSONObject();
//        bizContent.set("out_trade_no", aliPay.getTraceNo());  // 我们自己生成的订单编号
//        bizContent.set("total_amount", aliPay.getTotalAmount()); // 订单的总金额
//        bizContent.set("subject", aliPay.getSubject());   // 支付的名称
        // TODO 生成的订单号 从前端传入
        bizContent.set("out_trade_no", aliPay.getTraceNo());  // 我们自己生成的订单编号
        bizContent.set("total_amount", aliPay.getTotalAmount()); // 订单的总金额
        bizContent.set("subject", aliPay.getSubject());
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
        request.setBizContent(bizContent.toString());

        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String outTradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublicKey(), "UTF-8"); // 验证签名
            // 支付宝验签
            if (checkSignature) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 查询订单
                QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("order_id", outTradeNo);
                Orders orders = ordersMapper.selectOne(queryWrapper);

                if (orders != null) {
                    orders.setAlipayNo(alipayTradeNo);
                    orders.setPayTime(new Date());
                    orders.setState("已支付");
                    ordersMapper.updateById(orders);
                }
            }
        }
        return "success";
    }

    @GetMapping("/search")
    public JsonResult search(@RequestParam String tradeNo) {

/** 应用id，如何获取请参考：https://opensupport.alipay.com/support/helpcenter/190/201602493024 **/
        String APP_ID = "";

/** 应用私钥，如何获取请参考：https://opensupport.alipay.com/support/helpcenter/207/201602469554 **/
        String APP_PRIVATE_KEY = "";

/** 支付宝公钥，如何获取请参考：https://opensupport.alipay.com/support/helpcenter/207/201602487431 **/
        String ALIPAY_PUBLIC_KEY = "";

/** 初始化 **/
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, "9021000125605862",
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

/** 实例化具体API对应的request类，类名称和接口名称对应,当前调用接口名称：alipay.trade.query（统一收单线下交易查询）**/
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

/** 设置业务参数 **/
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();

/** 注：交易号（TradeNo）与订单号（OutTradeNo）二选一传入即可，如果2个同时传入，则以交易号为准 **/
/** 支付接口传入的商户订单号。如：2020061601290011200000140004 **/
        model.setOutTradeNo(tradeNo);

/** 异步通知/查询接口返回的支付宝交易号，如：2020061622001473951448314322 **/
//model.setTradeNo("2020061622001473951448314322");

/** 将业务参数传至request中 **/
        request.setBizModel(model);

/** 第三方调用（服务商模式），必须传值与支付接口相同的app_auth_token **/
//request.putOtherTextParam("app_auth_token", "传入获取到的app_auth_token值");

        AlipayTradeQueryResponse response = null;
        try {

/** 通过alipayClient调用API，获得对应的response类 **/
            response = alipayClient.execute(request);

        } catch (AlipayApiException e) {

            e.printStackTrace();
        }

/** 获取接口调用结果，如果调用失败，可根据返回错误信息到该文档寻找排查方案：https://opensupport.alipay.com/support/helpcenter/101 **/
        System.out.println(response.getCode());

        if (response.getCode().endsWith("10000")) {
            //交易号转换为Long类型
//            Long tradId=Long.parseLong(tradeNo);
//            repository.updateState(tradId);
            service.updateState(tradeNo);
            return JsonResult.ok(); // 根据你的需求，可能需要传递一些额外的数据给前端
        } else if (response.getCode().endsWith("40004")){
            // 在其他情况下返回错误信息
            String message="订单不存在";
            log.error(message);
            return JsonResult.fail(ServiceCode.ERROR_BAD_REQUEST,message); // 根据你的需求返回适当的错误信息
        }else return JsonResult.fail(ServiceCode.ERROR_BAD_REQUEST,"错误");

    }
}


